﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client; // for SharePoint 2010 
using ServerAPI = Microsoft.SharePoint;
using System.IO;

namespace ImportHub2007Content
{
    partial class Importer
    {
        private Dictionary<string, string> _availableProductsInTarget = null;
        private StreamWriter _logFile;
        private string _targetUrl = "";

        public bool IsSourceValid(string directoryPath)
        {
            return false;
        }


        private void Log(string message)
        {
            Console.WriteLine(message);

            if (_logFile != null)
            {
                _logFile.WriteLine(message);
            }
        }

        private bool AddProductToNavigation(string productTitle)
        {
            // this function requires access to SERVER APIs (Microsoft.SharePoint.Publishing) - import tool must be run from a server in the farm 
            bool addedNode = false;
            try
            {
                using (ServerAPI.SPSite siteCollection = new ServerAPI.SPSite(this._targetUrl))
                {
                    using (ServerAPI.SPWeb web = siteCollection.OpenWeb())
                    {
                        ServerAPI.Publishing.PublishingWeb pubWeb = ServerAPI.Publishing.PublishingWeb.GetPublishingWeb(web);
                        if (pubWeb != null)
                        {
                            ServerAPI.Navigation.SPNavigationNodeCollection nodes = pubWeb.Navigation.CurrentNavigationNodes;

                            // find the PRODUCT Heading node 
                            foreach (ServerAPI.Navigation.SPNavigationNode node in nodes)
                            {
                                if (node.Title.ToUpper() == "PRODUCTS")
                                {
                                    ServerAPI.Navigation.SPNavigationNode newNode = new ServerAPI.Navigation.SPNavigationNode(productTitle, "Pages/Product.aspx");
                                    node.Children.AddAsLast(newNode);
                                    newNode.Update(); // force the property bag to be created so we can set the UrlQueryString property
                                    newNode.Properties.Add("UrlQueryString", "Product=" + productTitle);
                                    newNode.Update();
                                    node.Update();
                                    addedNode = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception err)
            {
                Log("AddProductToNavigation: Failed with message : " + err.Message);
                Console.WriteLine("AddProductToNavigation: Failed with message : " + err.Message);
            }

            return addedNode;

        }

        private bool IsProductValid(string productTitle, out string productItemId)
        {
            productItemId = null;
            if (String.IsNullOrEmpty(productTitle))
            {
                return false;
            }

            if (productTitle.Contains(";#"))
            {
                productTitle = productTitle.Trim(';', '#');
            }

            if (_availableProductsInTarget == null)
            {
                _availableProductsInTarget = new Dictionary<string, string>();
                Microsoft.SharePoint.Client.ClientContext cc = new Microsoft.SharePoint.Client.ClientContext(this.TargetUrl);
                cc.Credentials = System.Net.CredentialCache.DefaultCredentials;
                Microsoft.SharePoint.Client.Web webHubSource = cc.Web;
                Microsoft.SharePoint.Client.List list = cc.Web.Lists.GetByTitle("Products");

                Microsoft.SharePoint.Client.CamlQuery camlQuery = new Microsoft.SharePoint.Client.CamlQuery();
                camlQuery.ViewXml = @"<View>
                <Query>
                  <OrderBy><FieldRef Name='Title' Ascending='TRUE'/></OrderBy>
                </Query>
                <RowLimit>900</RowLimit>
                </View>";


                Microsoft.SharePoint.Client.ListItemCollection listItems = list.GetItems(camlQuery);

                cc.Load(listItems,
                    items => items
                        .Include(
                            item => item["ID"],
                            item => item["Title"],
                            item => item["FullTitle"]));
                cc.ExecuteQuery();

                foreach (Microsoft.SharePoint.Client.ListItem productItem in listItems)
                {
                    _availableProductsInTarget.Add((string)productItem["Title"], productItem["ID"].ToString());
                }
            }

            if (_availableProductsInTarget.ContainsKey(productTitle))
            {
                productItemId = _availableProductsInTarget[productTitle];
            }
            else
            {
                productItemId = null;
            }

            return _availableProductsInTarget.ContainsKey(productTitle);

        }

        private int GetUserIdFromLogon(string logon)
        {
            int retVal = 0;
            try
            {
                Microsoft.SharePoint.Client.ClientContext cc = new Microsoft.SharePoint.Client.ClientContext(this.TargetUrl);
                cc.Credentials = System.Net.CredentialCache.DefaultCredentials;

                Microsoft.SharePoint.Client.Web webHubSource = cc.Web;
                Microsoft.SharePoint.Client.User lookupUser = cc.Web.EnsureUser(logon);

                cc.Load(lookupUser);
                cc.ExecuteQuery();

                retVal = lookupUser.Id;
            }
            catch (Exception)
            {
                Log("Could not determine user id for user logon: " + logon);
                Console.WriteLine("Could not determine user id for user logon: " + logon);
            }

            return retVal;
        }

        private bool IsTargetValid(string targetUrl)
        {
            if (!Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute)) { return false; }

            try
            {
                Microsoft.SharePoint.Client.ClientContext cc = new Microsoft.SharePoint.Client.ClientContext(targetUrl);
                cc.Credentials = System.Net.CredentialCache.DefaultCredentials;
                //cc.Credentials = new System.Net.NetworkCredential("devb", "Temp4u!!", "mss");

                Microsoft.SharePoint.Client.Web webHubSource = cc.Web;

                Microsoft.SharePoint.Client.List list = cc.Web.Lists.GetByTitle("Content Library");

                Microsoft.SharePoint.Client.CamlQuery camlQuery = new Microsoft.SharePoint.Client.CamlQuery();
                camlQuery.ViewXml = @"<View><Query></Query></View>";
                // <OrderBy><FieldRef Name='Modified' Ascending='TRUE'/></OrderBy><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>Test</Value></Eq></Where>

                Microsoft.SharePoint.Client.ListItemCollection listItems = list.GetItems(camlQuery);

                cc.Load(listItems,
                    items => items
                        .Include(
                             item => item["Title"],
                             item => item["Product"],
                             item => item["Abstract"],
                             item => item["AppearsInRotator"],
                             item => item["ThumbnailImageUrl"],
                             item => item["IsVideoContent"],
                             item => item["IsFeaturedContent"],
                             item => item["Difficulty"]));
                cc.ExecuteQuery();
                return true;

            }
            catch (Exception)
            {
                Log("Target URL could not be validated");
                Console.WriteLine("Target URL could not be validated");
                return false;
            }
        }
    }
}
